package com.gzz.orchid.common.webmvc.securityjwt;

import com.gzz.orchid.common.core.util.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;

import java.util.List;
import java.util.Objects;

/**
 * 实现动态权限逻辑
 * 在自定义的身份验证管理器中添加自定义的身份验证逻辑，
 * 例如从数据库中查询用户信息，然后进行密码匹配
 *
 * @author higmd
 */
@Slf4j
public class DelegateDynamicAuthenticationManager implements AuthenticationManager {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        log.info("用户登录: {} - {}", username, password);
        // 获取用户信息
        User user = getUser(username, password);
        if (Objects.isNull(user)) {
            throw new BadCredentialsException(I18nUtil.message("用户不存在"));
        }
        if (!user.getPassword().equals(password)) {
            throw new BadCredentialsException(I18nUtil.message("密码错误"));
        }
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
        return new UsernamePasswordAuthenticationToken(username, password);
    }

    public User getUser(String username, String password) {
        return new User(username, password, null);
    }
}
